/**
 *  *2010-5-2 下午02:11:01  add 
 */
package com.base.myproject.server.jbpm;

import org.jbpm.api.IdentityService;

import com.base.myproject.server.tools.DataSetTool;

/**
 * @author Administrator 2010-5-2 javazgw@gmail.com
 */
public class JbpmGroup {
	static JbpmGroup jbpmgroup;

	private JbpmGroup() {
		init();
	}

	public static JbpmGroup getInstance() {
		if (jbpmgroup == null)
			jbpmgroup = new JbpmGroup();
		return jbpmgroup;

	}

	void init() {
		test();
	}

	void test() {
		IdentityService identityService = JbpmPE.getInstance().getPe()
				.getIdentityService();
		if (findisHaveGroupbyName("sales-dept"))
			identityService.createGroup("sales-dept");

		if (findisHaveUserbyName("zgw"))
			identityService.createUser("zgw", "", "");

		createMembership("zgw", "sales-dept");

	}

	/**
	 * 判断是否存在groupname这个组， 根据名字匹配
	 * 
	 * @param groupname
	 * @return
	 */
	boolean findisHaveGroupbyName(String groupname) {
		String str = "select count(*) as c from jbpm4_id_group where name_='"
				+ groupname + "'";
		DataSetTool dst = new DataSetTool();
		if (!dst.getDataSet(str).getValue(0, "c").equals("0"))
			return false;
		else
			return true;

	}

	/**
	 * 根据业务系统的userid查找是否工作流里也存在改用户 根据用户编码进行查找
	 * 
	 * @param userid
	 * @return
	 */
	boolean findisHaveUserbyName(String userid) {
		String str = "select count(*) as c from jbpm4_id_user where id_='"
				+ userid + "'";
		DataSetTool dst = new DataSetTool();
		if (!dst.getDataSet(str).getValue(0, "c").equals("0"))
			return false;
		else
			return true;
	}

	/**
	 * 根据组名，用户名判读是否存在 组--用户 的关系
	 * 
	 * @param groupname
	 * @param userid
	 * @return
	 */
	boolean findisHaveMenberShip(String groupname, String userid) {
		String str = "select count(*) as c from jbpm4_id_membership where exists ";
		str += " (select * from jbpm4_id_group where jbpm4_id_group.dbid_=jbpm4_id_membership.group_  ";
		str += "and jbpm4_id_group.name_='"+groupname+"' ";
		str += " ) and exists (select * from jbpm4_id_user where jbpm4_id_user.dbid_=jbpm4_id_membership.user_ ";
		str += " and jbpm4_id_user.id_='"+userid+"' )";
		DataSetTool dst = new DataSetTool();
		if (!dst.getDataSet(str).getValue(0, "c").equals("0"))
			return false;
		else
			return true;

	}
	/**
	 * 建立用户与组的关系
	 * 如果组不存在则添加组
	 * 如果用户不存在则添加用户
	 * 如果组与用户关系不存在则添加关系
	 * @param userid
	 * @param groupname
	 */

	void createMembership(String userid, String groupname) {
		
		if (findisHaveGroupbyName(groupname))
			JbpmPE.getInstance().getPe().getIdentityService().createGroup(groupname);

		if (findisHaveUserbyName(userid))
			JbpmPE.getInstance().getPe().getIdentityService().createUser(userid, "", "");
		
		if(findisHaveMenberShip( groupname,  userid) )
			JbpmPE.getInstance().getPe().getIdentityService().createMembership(
				userid, groupname, "base");
	}
}
